package java.util.concurrent;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * CyclicBarrier 运行一组线程全部进入等待状态后, 同时释放等待状态
 * 构造方法有两个
 * 第一个必选参数: 参与者的总数 ( await() 次数达到该值后, 所有等待中的线程同时释放)
 * 第二个可选参数: Runnable. 当最后一个线程调用 await() 后, 所有等待线程释放之前, 会回调该方法
 * cyclicbarrier 支持自动重用 (无需显式 reset 就可以自动重用了)
 */
public class CyclicBarrier {

    /**
     * 触发释放会消耗一个 Generation
     * reset 会生成一个新的 Generation
     */
    private static class Generation {
        boolean broken = false;
    }

    /** 栅栏的锁 */
    private final ReentrantLock lock = new ReentrantLock();

    /** 等待直到触发 条件 */
    private final Condition trip = lock.newCondition();

    /** 参与者数量 */
    private final int parties;

    /* 最后一个线程 await() 后, 所有线程释放前的回调 */
    private final Runnable barrierCommand;

    /** 当前的 generation */
    private Generation generation = new Generation();

    /**
     * 仍旧等待的参与者数量
     * 从参与者数量倒数到 0
     */
    private int count;

    /**
     * Updates state on barrier trip and wakes up everyone.
     * Called only while holding lock.
     */
    private void nextGeneration() {
        // signal completion of last generation
        trip.signalAll();
        // set up next generation
        count = parties;
        generation = new Generation();
    }

    /**
     * Sets current barrier generation as broken and wakes up everyone.
     * Called only while holding lock.
     */
    private void breakBarrier() {
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }

    /**
     * 主要的屏障代码, 覆盖了多种策略
     */
    private int dowait(boolean timed, long nanos)
        throws InterruptedException, BrokenBarrierException,
               TimeoutException {
        final ReentrantLock lock = this.lock;
        // 上锁
        lock.lock();
        try {
            final Generation g = generation;

            if (g.broken)
                throw new BrokenBarrierException();

            if (Thread.interrupted()) {
                breakBarrier();
                throw new InterruptedException();
            }

            // 自减
            int index = --count;

            // 最后一个线程 await()
            // 触发所有线程释放
            if (index == 0) {  // tripped
                boolean ranAction = false;
                try {
                    // 释放前, 先回调构造方法中传入的 Runnable
                    final Runnable command = barrierCommand;
                    if (command != null)
                        command.run();
                    ranAction = true;
                    // 声明新的 Generation
                    nextGeneration();
                    return 0;
                } finally {
                    if (!ranAction)
                        breakBarrier();
                }
            }

            // loop until tripped, broken, interrupted, or timed out
            for (;;) {
                try {
                    if (!timed)
                        trip.await();
                    else if (nanos > 0L)
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    if (g == generation && ! g.broken) {
                        breakBarrier();
                        throw ie;
                    } else {
                        // We're about to finish waiting even if we had not
                        // been interrupted, so this interrupt is deemed to
                        // "belong" to subsequent execution.
                        Thread.currentThread().interrupt();
                    }
                }

                if (g.broken)
                    throw new BrokenBarrierException();

                if (g != generation)
                    return index;

                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }

            // 最后释放锁
        } finally {
            lock.unlock();
        }
    }

    /**
     *
     * @param parties 屏障打开之前, 需要调用 await() 的次数
     * @param barrierAction 所有线程释放之前, 会回调该方法
     */
    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }

    public CyclicBarrier(int parties) {
        this(parties, null);
    }

    /**
     * 越过屏障的参与者数量
     */
    public int getParties() {
        return parties;
    }


    public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen
        }
    }

    public int await(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }

    /**
     * 屏障是否是打破的状态
     */
    public boolean isBroken() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return generation.broken;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 重置屏障为初始状态
     */
    public void reset() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            breakBarrier();   // break the current generation
            nextGeneration(); // start a new generation
        } finally {
            lock.unlock();
        }
    }

    /**
     * 返回正在等待的参与者数量
     */
    public int getNumberWaiting() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return parties - count;
        } finally {
            lock.unlock();
        }
    }
}
